﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using log4net;
using StockFinder.Model;
using StockFinder.Network;

namespace StockFinder.YahooFinance
{
    /// <summary>
    /// Downloads the price history for a given symbol or list of symbols
    /// and saves to a location
    /// </summary>
    public class YahooFinanceOnlineStockPriceHistoryDownloader
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(YahooFinanceOnlineStockPriceHistoryDownloader)); 

        const string BASE_URL = "http://ichart.finance.yahoo.com/table.csv?s={0}&amp;d={1}&amp;e={2}&amp;f={3}&amp;g=d&amp;a={4}&amp;b={5}&amp;c={6}&amp;ignore=.csv";
        const string PAGE_NOT_EXIST = "Sorry, the page you requested was not found";

        public string DownloadSymbolPricesCsv(Symbol symbol, DateTime fromDate, DateTime toDate)
        {
            var success = false;
            string pageSource = null;

            //create the url
            var pricesUrl = string.Format(
                BASE_URL,
                Utils.Formatted(symbol),
                toDate.Month - 1,
                toDate.Day,
                toDate.Year,
                fromDate.Month - 1,
                fromDate.Day,
                fromDate.Year);            

            using (var webClient = new ProxiedWebClient())
            {
                try
                {                            
                    pageSource = webClient.DownloadString(pricesUrl);

                    success = true;
                }
                catch (Exception exception)
                {
                    Log.ErrorFormat("Error reading webpage source for '{0}:{1}'. {2}", 
                        symbol.Name, 
                        pricesUrl,
                        exception);
                }
            }

            //was the page hit a success?
            if (success)
            {
                /* check that prices exist for this symbol */

                if (string.IsNullOrEmpty(pageSource) || pageSource.IndexOf(PAGE_NOT_EXIST) > -1)
                {
                    Log.WarnFormat("No prices exist");
                }
            }

            return pageSource;
        }
       
        public void DownloadAndSaveSymbolPricesCsv(Symbol symbol, DateTime fromDate, DateTime toDate, 
            string saveDirectory)
        {
            var symbolPrices = DownloadSymbolPricesCsv(symbol, fromDate, toDate);

            if (!string.IsNullOrEmpty(symbolPrices))
            {
                var filename = symbol.Name.Replace("/", ".") + ".csv";
                var path = Path.Combine(saveDirectory, filename);

                Log.DebugFormat("Saving symbol prices to: {0}", path);

                try
                {
                    File.WriteAllText(path, symbolPrices);
                }
                catch (Exception exception)
                {
                    Log.Error(exception);                    
                }                
            }
        }
    }
}
